<?php
/**
 *
 *
 *  Configurable properties of Yz_Property_Interface:
 *
 *  - source: the alias of an SQL table, which corresponds with the list of SQL tables for an item
 *  - selectField: SQL field clause w/o alias (eg. LEFT(:field,10) )
 *  - updateField: SQL field name
 *  - updateValue: SQL rvalue(can contain a field parameter), eg. :name, REPLACE(:field, 'a', 'b')
 *  - insertField, insertValue
 *  - {actionName}Field, {actionName}Value
 *
 */
abstract class Yz_Property_Abstract
    extends Yz_Object
    implements Yz_Property_Interface
{

    protected $name;
    protected $config = array();
    protected $formElementType;



    /**
     *
     */
    public function __construct( $name, $config=null )
    {
        debug();
        $this->name = Yz_String::testNotEmpty($name);
        if (null !== $config) {
            $this->config = Yz_Hash::valueOf($config);
        }
    }

    public function assign($value)
    {
        return $value;
    }

    /**
     *
     */
    public function getName()
    {
        return $this->name;
    }

    public function getFormElementType()
    {
        $p = $this->defaultGetter('formElementType');
        return null === $p ? $this->formElementType : $p;
    }

    /**
     *
     */
    public function getSelect()
    {
        if ($this->indexExists('select')) {
            $val = $this->config['select'];
            assert( 'is_scalar($val)' );
            if ('' !== (string)$val) {
                $val .= ' AS ' . $this->name;
            }
            return $val;
        }
        return $this->getSource() . '.' . $this->name;
    }

    public function getUpdate()
    {
        if ($this->indexExists('update')) {
            return $this->config['update'];
        }
        return ':' . $this->name;
    }

    public function getInsert()
    {
        if ($this->indexExists('insert')) {
            return $this->config['insert'];
        }
        return ':' . $this->name;
    }

    /**
     *  get the source name for the property (the SQL alias of an SQL table name)
     *  Ensure that the source name is a string (or null)
     *  @return string|null
     */
    public function getSource()
    {
        return $this->defaultGetter('source');
    }

    protected function defaultGetter($var)
    {
        if ($this->indexExists($var)) {
            return $this->config[$var];
        }
        return null;
    }
    protected function indexExists($var)
    {
        return array_key_exists($var, $this->config);
    }
}
